<template>
  <div class="page-container">
    <el-card class="box-card">
      <!-- 筛选表单 -->
      <div class="table-filter">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item label="代理id:">
            <el-input clearable style="width: 120px" v-model="filterForm.agencyId" placeholder="请输入代理id" />
          </el-form-item>
          <el-form-item label="托管地址:">
            <el-input clearable style="width: 120px" v-model="filterForm.address" placeholder="请输入托管地址" />
          </el-form-item>
          <!--    <el-form-item label="变动余额类型:">
                        <el-select clearable style="width: 120px" v-model="filterForm.changeBalanceType"
                            placeholder="请选择">

                            <el-option label="trx" value="1" />
                            <el-option label="usdt" value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="变动类型:">
                        <el-select v-model="filterForm.changeType" placeholder="请选择">

                            <el-option label="充值" value="0" />
                            <el-option label="提现" value="1" />
                            <el-option label="支出" value="2" />
                            <el-option label="闪充收入" value="3" />
                            <el-option label="闪兑收入" value="4" />
                            <el-option label="笔数收入" value="5" />
                        </el-select>
                    </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮 -->
      <!-- <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon></el-button>
      </div> -->
      <div class="content-container">
        <!-- 左侧代理菜单 -->
        <AgentFilterMenu v-if="!isMobile" :active-agent-id="filterForm.agencyId" @select-agent="handleAgentSelect"
          class="agent-menu-container" />

        <!-- 右侧表格 -->
        <div class="table-container">
          <!-- 表格 -->
          <el-table v-loading="loading" :data="tableData" border style="width: 100%; overflow-y: auto"
            @selection-change="handleSelectionChange">
            <el-table-column prop="agencyId" label="代理id" :width="isMobile ? 105 : null" />
            <el-table-column prop="tgUserId" label="tg用户id" :width="isMobile ? 105 : null" />
            <el-table-column prop="address" label="托管地址" :width="isMobile ? 200 : 220">
              <template #default="scope">
                <CopyableAddressVue :value="scope.row.address" :maxLength="16" />
              </template>
            </el-table-column>
            <el-table-column prop="allUseEnergy" label="总能量数" :width="isMobile ? null : 120" />
            <el-table-column prop="useEnergy" label="剩余能量数" :width="isMobile ? 100 : 120" />
            <el-table-column prop="allUseNet" label="总带宽数" :width="isMobile ? 80 : 120" />
            <el-table-column prop="useNet" label="剩余带宽数" :width="isMobile ? 95 : 120" />
            <el-table-column prop="trustType" label="托管类型" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.trustType === -1
                  ? 'info'
                  : scope.row.trustType === 0
                    ? 'danger'
                    : scope.row.trustType === 1
                      ? 'warning'
                      : 'success'
                  ">
                  {{
                    scope.row.trustType === -1
                      ? "全关闭"
                      : scope.row.trustType === 0
                        ? "全部"
                        : scope.row.trustType === 1
                          ? "能量托管"
                          : "带宽托管"
                  }}
                </el-tag></template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" :width="isMobile ? 155 : null" />
          </el-table>

          <el-pagination class="pagination" :class="{ 'mobile-pagination': isMobile }"
            :current-page="pagination.currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pagination.pageSize"
            :layout="paginationLayout" :total="pagination.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from "vue";
import AgentFilterMenu from "../../components/AgentFilterMenu.vue";
import api from "../../network/api";
import { ElMessage } from "element-plus";
import { useWindowSize } from "@vueuse/core";

import CopyableAddressVue from "../../components/CopyableAddress.vue";
export default {
  components: {
    AgentFilterMenu,
    CopyableAddressVue,
  },
  setup() {
    const isMobile = computed(() => windowWidth.value < 768);
    const { width: windowWidth } = useWindowSize();
    const filterForm = ref({
      agencyId: "",
      address: "",
      // changeBalanceType: "",
      // changeType: "",
    });

    const tableData = ref([]);
    const loading = ref(false);
    const multipleSelection = ref([]);
    const botIdWidth = ref(0);

    const lastFetchParams = ref(null);
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });
    const paginationLayout = computed(() => {
      if (windowWidth.value < 768) {
        return 'sizes, prev, pager, next';
      } else {
        return 'total,sizes, prev, pager, next, jumper';
      }
    });
    const handleAgentSelect = (agentId) => {
      filterForm.value.agencyId = agentId;
      onSearch();
    };
    // 格式化余额显示
    const formatBalance = (balance) => {
      // 检查是否为空值（null、undefined或空字符串）
      if (balance == null || balance === "") {
        return 0;
      }

      return Number(balance / 1e6).toLocaleString("zh-CN", {
        maximumFractionDigits: 10,
      });
    };
    const calculateColumnWidths = () => {
      const measureElement = document.createElement("span");
      measureElement.style.position = "absolute";
      measureElement.style.visibility = "hidden";
      measureElement.style.whiteSpace = "nowrap";
      document.body.appendChild(measureElement);

      const getTextWidth = (text) => {
        measureElement.textContent = text;
        return measureElement.offsetWidth;
      };

      let maxBotIdWidth = 0;
      // let maxBotUsernameWidth = 0;
      // let maxBotPathWidth = 0;

      // 计算表头宽度
      maxBotIdWidth = Math.max(maxBotIdWidth, getTextWidth("变动类型"));
      // maxBotUsernameWidth = Math.max(maxBotUsernameWidth, getTextWidth('代理机器人名称'));
      // maxBotPathWidth = Math.max(maxBotPathWidth, getTextWidth('代理机器人路由'));

      // 计算表格数据宽度
      tableData.value.forEach((row) => {
        maxBotIdWidth = Math.max(maxBotIdWidth, getTextWidth(row.changeType));
        // maxBotUsernameWidth = Math.max(maxBotUsernameWidth, getTextWidth(row.botUsername));
        // maxBotPathWidth = Math.max(maxBotPathWidth, getTextWidth(row.botPath));
      });

      // 适当增加一些间距
      botIdWidth.value = maxBotIdWidth + 35;
      // botUsernameWidth.value = maxBotUsernameWidth + 7 ;
      // botPathWidth.value = maxBotPathWidth + 20;

      document.body.removeChild(measureElement);
    };

    watch(
      tableData,
      () => {
        calculateColumnWidths();
      },
      { immediate: true }
    );

    // 获取代理列表
    const fetchAgencyList = () => {
      const params = {
        pageNum: pagination.value.currentPage,
        pageSize: pagination.value.pageSize,
        ...filterForm.value,
      };
      const isSameAsLast =
        JSON.stringify(params) === JSON.stringify(lastFetchParams.value);

      if (isSameAsLast) {
        // console.log("参数未变化，跳过请求");
        return;
      }

      loading.value = true;
      api
        .order_penThirdUserList(params)
        .then((res) => {
          // console.log("order_penThirdUserList:", res.data);
          if (res.data.code === 99999 && res.data.success) {
            // 关键修复：使用 res.data.data.list 而不是 res.data.list
            tableData.value = res.data.data.list;
            pagination.value.total = res.data.data.total;
            lastFetchParams.value = params;
          } else {
            // ElMessage.error(res.msg || "获取代理列表失败");
          }
        })
        .catch((error) => {
          console.error("获取代理列表出错:", error);
          ElMessage.error("请求失败，请稍后重试");
        })
        .finally(() => {
          loading.value = false;
        });
    };

    // 搜索
    const onSearch = () => {
      const hasChanges = Object.keys(filterForm.value).some(
        (key) =>
          filterForm.value[key] !== (lastFetchParams.value?.[key] ?? null)
      );

      if (!hasChanges && pagination.value.currentPage === 1) {
        // ElMessage.info("搜索条件未变化");
        return;
      }

      pagination.value.currentPage = 1;
      fetchAgencyList();
    };

    // 重置筛选
    const resetFilter = () => {
      const isAlreadyReset = Object.values(filterForm.value).every(
        (val) => val === null
      );

      if (isAlreadyReset) {
        // ElMessage.info("已处于重置状态");
        return;
      }
      filterForm.value = {
        agencyId: '',
        address: '',
        // changeBalanceType: null,
        // changeType: null,
      };
      onSearch();
    };

    // 表格选择
    const handleSelectionChange = (val) => {
      multipleSelection.value = val;
    };

    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size;
      fetchAgencyList();
    };

    // 当前页变化
    const handleCurrentChange = (page) => {
      pagination.value.currentPage = page;
      fetchAgencyList();
    };

    // 新增用户
    const handleAdd = () => {
      ElMessage.info("新增代理");
    };

    // 编辑用户
    const handleEdit = (row) => {
      ElMessage.info(`编辑代理: ${row.botUsername}`);
    };

    onMounted(() => {
      fetchAgencyList();
    });

    return {
      filterForm,
      tableData,
      loading,
      multipleSelection,
      pagination,
      onSearch,
      resetFilter,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      formatBalance,
      isMobile,
      botIdWidth,
      handleAgentSelect,
      paginationLayout
    };
  },
};
</script>

<style scoped lang="less">
.box-card {
  width: 100%;
  height: 90vh;
  overflow-y: auto;
  display: flex;
  // flex: 1;
  flex-direction: column;

  &::-webkit-scrollbar {
    width: 1px;
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(248, 248, 250, 0.2);
    border-radius: 6px;
    transition: background 0.3s;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  // background: #daddba;

  .demo-form-inline {
    // float: left;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    flex: 1;
    margin-bottom: 0;
  }

  .content-container {
    display: flex;
    flex: 1;
    flex-direction: row;
  }

  .agent-menu-container {
    width: 240px;
    margin-right: 16px;
    flex-shrink: 0;
    max-height: 79.9vh;
  }

  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
    max-height: 79.9vh;

    .el-table {
      flex: 1;
      max-height: 80vh;

    }

    .pagination {
      margin-top: 15px;
      float: right !important;
      display: flex;
      justify-content: flex-end;
      width: 100%;
    }
  }
}

@media screen and (max-width: 768px) {
  .box-card {
    height: auto;
    background: #fff;
    height: 88vh;
    overflow-y: auto;

    .content-container {
      flex-direction: column;
      // background: #b34747;
      height: auto;
      // overflow-y: auto;
    }

    .agent-menu-container {
      width: 100%;
      margin-right: 0;
      margin-bottom: 16px;
      /* 移动端固定高度 */
      height: 300px;
    }

    .table-container {
      width: 95%;
      height: auto;
    }

    .pagination {
      float: none !important;
      display: flex;
      justify-content: center;
      margin-top: 15px;
    }
  }

  /* 移动端表格样式调整 */
  :deep(.el-table__header) .el-table__cell {
    white-space: nowrap !important;
    text-overflow: clip !important;
    overflow: visible !important;
  }

  :deep(.el-table__header-wrapper) th>.cell {
    white-space: nowrap !important;
    overflow: visible !important;
    text-overflow: clip !important;
    display: inline-block;
    width: auto;
  }

  :deep(.el-table__body) .el-table__cell {
    white-space: nowrap !important;
    text-overflow: clip !important;
    overflow: visible !important;
  }

  .mobile-pagination {
    :deep(.el-pagination) {
      display: flex !important;
      flex-wrap: nowrap !important;
      overflow-x: auto !important;
      padding: 5px 0 !important;
      min-height: 32px !important;
      font-size: 12px !important;

      .el-pagination__sizes {
        font-size: 12px !important;
        transform: scale(0.9) !important;
        transform-origin: left center !important;
        white-space: nowrap !important;
        margin-right: 5px !important;
      }

      .btn-prev,
      .btn-next {
        min-width: 24px !important;
        height: 24px !important;
        padding: 0 5px !important;
        margin: 0 2px !important;
      }

      .el-pager {
        li {
          min-width: 24px !important;
          height: 24px !important;
          line-height: 24px !important;
          font-size: 12px !important;
          padding: 0 3px !important;
          margin: 0 2px !important;
        }
      }

      .el-pagination__jump {
        margin-left: 5px !important;
        font-size: 12px !important;

        .el-pagination__editor {
          width: 40px !important;

          .el-input__inner {
            height: 24px !important;
            padding: 0 5px !important;
            font-size: 12px !important;
          }
        }
      }
    }
  }

  /* 强制覆盖Element UI默认样式 */
  :deep(.el-pagination) {
    --el-pagination-button-width: 24px !important;
    --el-pagination-button-height: 24px !important;
    --el-pagination-font-size: 12px !important;
  }

  :deep(.el-pagination button, .el-pagination li) {
    min-width: 24px !important;
    height: 24px !important;
    line-height: 24px !important;
    font-size: 12px !important;
  }

  :deep(.el-pagination__editor) {
    height: 24px !important;

    .el-input__inner {
      height: 24px !important;
      font-size: 12px !important;
    }
  }
}
</style>
